package com.newcapec.common.utils.iot;

/*import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;*/

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

/**
 * 使用DES加密和解密的方法
 */
public class DesTools {

    // private final byte[] DESkey = "A1A2A3A4".getBytes("UTF-8");// 设置密钥，略去
    // private final byte[] DESIV = {0x11, 0x12, 0x23, 0x33, (byte) 0x90, (byte)
    // 0xAC, (byte) 0xBD, (byte) 0xBF};// 设置向量，略去

    private final byte[] DESkey = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};

    private final byte[] DESIV = {0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01};

    private static AlgorithmParameterSpec iv = null;// 加密算法的参数接口，IvParameterSpec是它的一个实现
    private static Key key = null;


    public static void main(String[] args) {
        try {
            String s1 = "{\"contract_no\":\"20195314536915555001\",\"user_id\":\"2088712006091019\"}";
            // DesTools dt = new DesTools("7482a46f29a44494a0de1fa2d1df9c14",
            // 1);
            DesTools dt = new DesTools("b751fa75ccb2400bbd5aa54e2dcf071e", 1);
            String s2 = dt.encode(s1);
            System.out.println(s2);
            // System.out.println(dt.decodeFromHex(s2));
            // String s =
            // "6E514A1E230A395ABE3D960D7D1EBFF92E061A4EAC48C06BF3924F61941E672B9882F9FED2A044EBE5935408C2CD61C8254E2D41860DDC4634E1C3DC4F9FB2545344115704CFD8C0F210A3F676FFA757C56A151C314ADF8F44E75E2576154E4E31CEC203A5FD7DB5669FCC9216FF35EFC7299FDB8E6B3413B81E0EFCDAF13A341D66396822C31369D3513CAF9B6C62B979E9AD7CF91B33F095ECE0D9645921AD649997E8824C1776328F082D8F02C558787009574D62C64FEF3351111F6EE403214A524155E5F7CAD93EAE0AC6CBC13372DB4F43387F2E7A9DAC1D58A3966EEED453DBC0A0AEFFC45036495D4E48A1C0D2DE4ED9585DF80604D4BB9ECD056A59D66064350049EB178CA77073A5C58CECB4822AF96D037A712B3C0E58980BA1F6A7A6955516A5CAF82A8B7FBA6F7D970D0DBFE76D90A00BC20A72FF7344E6A4018FC7D967C4A04F1C7754EAABC62BB3E57C2D4232B0C240123650B02E1BDCF0294750DA2D6577DC129C058D2AB1F7597ABBF38CFAAFCC59C7EBBEAF20F15472E9D97C1C6006D5CA64BE299C5918F0B4AA346851178764BC1494B457B38BD8215A81A7B2FBBC21D9E53F9A50AA442752A964BC1065E670B5E1B282B4094726C9E63D459C361B6E825AFD3D33988A1174AE7FB02E7758EBC1A105325E418C98A81AEAFAE36AE36C6E08CA945BA560FEC61AFE74260FDCB81FEB05068704E8D3B529849D75CFF1721E963B96F7EEE4DFE1CFB610E92972CCD509FAB1DAE3EF0A257F7B149AA1730C065C7FD812A5DA1085CB602B0F50D1E46327CDB6A685282FF628608AA6E6D3747DBBD8BCEB5EA6E4B77FDAE716E09A457941173508AA3B66AB2463509397B965A3419EC0C318DCFD66AA222BB07A513FA8F1A5EDA2AC163530D6015C09FDCA351B5D5D9162A4031C3F66B4BACDDDAAB72A6AEE2A009CBAAE9FFA33EF6EA55656364B0DC0C66225C3F3978A79940B0569047E2990971BCA2B9F7C38338B8E454DF633F5850E80F65AB9F066E2D21D27858CA71C758680ED19C0467C09E4768C7F37967D521ABCBE10444E0AACCCD2E179E16A3F4D550C2E413BDD1CF13EBA9253415B0785B9A9A43A4BCE09D77F3FB6B616AA05FD1EC89502AAFF733096EB073A8327DFDA17E5730C6014BBE7A56D3A36416D1CFC61FECD4FDF126D832C31C1C89BA35AD4A7B5DF4714614DC6F8ECAFB9C404";
            // System.out.println(dt.decodeFromHex(s));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 默认key加解密
     */
    public DesTools() {
        try {
            DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
            iv = new IvParameterSpec(DESIV);// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            key = keyFactory.generateSecret(keySpec);// 得到密钥对象
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 自定义key加解密----缴费App使用----payController
     *
     * @param keyStr
     */
    public DesTools(String keyStr, int flag) {
        try {
            byte[] deskeys = Base64.decode(keyStr);
            // byte[] deskeys = hexStringToByteArray(keyStr);
            byte[] deskeys2 = new byte[8];
            System.arraycopy(deskeys, 0, deskeys2, 0, 8);
            DESKeySpec keySpec = new DESKeySpec(deskeys2);// 设置密钥参数
            iv = new IvParameterSpec(DESIV);// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            key = keyFactory.generateSecret(keySpec);// 得到密钥对象
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 自定义key加解密----三方下单接口使用
     *
     * @param keyStr
     */
    public DesTools(String keyStr) {
        try {

            byte[] deskeys = strToByteArray(keyStr);
            DESKeySpec keySpec = new DESKeySpec(deskeys);// 设置密钥参数
            iv = new IvParameterSpec(DESIV);// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            key = keyFactory.generateSecret(keySpec);// 得到密钥对象
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 自定义key加解密----三方下单接口使用
     *
     * @param deskeys
     */
    public DesTools(byte[] deskeys) {
        try {
            DESKeySpec keySpec = new DESKeySpec(deskeys);// 设置密钥参数
            iv = new IvParameterSpec(DESIV);// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            key = keyFactory.generateSecret(keySpec);// 得到密钥对象
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 自定义deskey和iv
     *
     * @param desKey
     * @param desIv
     */
    public DesTools(String desKey, String desIv) {
        try {
            byte[] deskeys = str2Ascii2Byte(desKey);
            DESKeySpec keySpec = new DESKeySpec(deskeys);// 设置密钥参数
            iv = new IvParameterSpec(str2Ascii2Byte(desIv));// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            key = keyFactory.generateSecret(keySpec);// 得到密钥对象
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private byte[] str2Ascii2Byte(String str) throws UnsupportedEncodingException {
        return StringUtil.str2Ascii2bytes(str);
    }

    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static String encode(String data) throws Exception {
        Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
        enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
        byte[] pasByte = enCipher.doFinal(data.getBytes("UTF-8"));
 /*       BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(pasByte);*/
        java.util.Base64.Encoder base64Encoder = java.util.Base64.getEncoder();
        return base64Encoder.encodeToString(pasByte);

    }

    /**
     * 对字节进行加密 返回base64字符串
     *
     * @param data
     * @return
     */
    public String encode(byte[] data) throws Exception {
        Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
        enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
        byte[] pasByte = enCipher.doFinal(data);
      /*  BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(pasByte);*/
        java.util.Base64.Encoder base64Encoder = java.util.Base64.getEncoder();
        return base64Encoder.encodeToString(pasByte);
    }

    /**
     * 解密
     *
     * @param data
     * @return
     */
    public String decode(String data) throws Exception {
        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        deCipher.init(Cipher.DECRYPT_MODE, key, iv);
       /* BASE64Decoder base64Decoder = new BASE64Decoder();

        byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));*/
        java.util.Base64.Decoder base64Decoder = java.util.Base64.getDecoder();
        byte[] pasByte = deCipher.doFinal(base64Decoder.decode(data));
        return new String(pasByte, "UTF-8");
    }

    /**
     * 解密字节为16进制字符
     *
     * @param data
     * @return
     */
    public String decode(byte[] data) throws Exception {
        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        deCipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] pasByte = deCipher.doFinal(data);
        return StringUtil.byte2HexString(pasByte);
    }

    /**
     * 解密base64后的字符串至16进制串
     *
     * @param data
     * @return
     */
    public String decodeToHex(String data) throws Exception {
        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        deCipher.init(Cipher.DECRYPT_MODE, key, iv);
        //BASE64Decoder base64Decoder = new BASE64Decoder();
        //byte[] aa = base64Decoder.decodeBuffer(data);
        java.util.Base64.Decoder base64Decoder = java.util.Base64.getDecoder();
        byte[] aa = base64Decoder.decode(data);
        byte[] pasByte = deCipher.doFinal(aa);

        return StringUtil.byte2HexString(pasByte);
    }

    /**
     * 对字符串加密后返回16进制数
     *
     * @param data
     * @return
     */
    public String encodeToHex(String data) throws Exception {
        Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
        enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
        byte[] pasByte = enCipher.doFinal(data.getBytes("UTF-8"));
        return StringUtil.byte2HexString(pasByte);
    }

    /**
     * 对字节加密后返回16进制数
     *
     * @param data
     * @return
     */
    public String encodeToHex(byte[] data) throws Exception {
        Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
        enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
        byte[] pasByte = enCipher.doFinal(data);
        return StringUtil.byte2HexString(pasByte);
    }

    public String decodeFromHex(String hexdata) throws Exception {
        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        deCipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] aa = StringUtil.hexToByteArray(hexdata);
        byte[] pasByte = deCipher.doFinal(aa);
        return new String(pasByte, "UTF-8");
    }

    /**
     * 解密16进制数据后 返回16进制数
     *
     * @param hexdata
     * @return
     */
    public String decodeFromHexToHex(String hexdata) throws Exception {
        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        deCipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] aa = StringUtil.hexToByteArray(hexdata);
        byte[] pasByte = deCipher.doFinal(aa);
        return StringUtil.byte2HexString(pasByte);
    }

    /**
     * String转换byte数组
     *
     * @param str
     * @return
     */
    public static byte[] strToByteArray(String str) {
        if (str == null) {
            return null;
        }
        byte[] byteArray = str.getBytes();
        return byteArray;
    }

    public static byte[] base64String2ByteFun(String base64Str) {
        return Base64.decode(base64Str);
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] b = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            b[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return b;
    }

    private static String formatInteger(int num) {
        String str = num + "";
        StringBuffer stringbuff = new StringBuffer();
        for (int i = 0; i < 8 - str.length(); i++) {
            stringbuff.append("0");
        }
        stringbuff.append(str);
        return stringbuff.toString();
    }

    /**
     * 使用带key带flag构造des
     *
     * @return
     */
    private static void desWithKsyAndFlag() throws Exception {
        String base64Str = "05B5AB8B1E8A6FDA82C3012E900B1482";
        DesTools des = new DesTools(base64Str, 1);// 自定义密钥
        String encodeStr = "{\"termid\":\"8\",\"acccode\":\"210\",\"out_trade_no\":\"XKP20171013173855260\",\"dpcode\":\"00000000\",\"opdt\":\"2017-10-24 10:07:52\",\"order_mode\":\"nomalpay\",\"appid\":100,\"customerid\":\"15\",\"opfare\":\"10\",\"scene_info\":\"缴费\"}";
        String decodeStr = "xUrm1ezlonCUBYVMLA3DkypJAUnXT11EAnr0F8Z5nTFvRmfNXAPiDX+KKg8hDmeW7HIzV2dzxh7P\r\nV7hlJwq6c7NK7r0t74WoOeI+yTQpgLWoXbo/ycdibMo2vKvopGR3U4XC1l9UC7oPNQxL3A8o2WY3\r\noRQjWs61yorj39sizdi+40KOcNeEYYYLEsOLQuI1hJ95EVsKkB11Ugjh4vv3hMoC49noGuaWg58D\r\nq4MV+pA6fKCb8f121aIIH60D49xCi7/5+EjAF1qw0ci0U8B0USTocK2c08E3zhl05/sHXAO5exRt\r\njjtV3uANWgRakm2kCnR7dqXEblvEiYsa6DDpJCLeHkUef98nS1jSAOv2lWLfdbMxF/Ydvh9XX5L0\r\n8nJp+zAwKsbKg4DaD0m5yOcfvn7CkdFsgl8rJgBY96E0D5bdcxP31TQwvrKb47M3iaL8fgxLeaM8\r\ndK7ZMQzZ+GWiZA==";
        System.out.println("下单data加密：" + des.encode(encodeStr));
        System.out.println("下单结果data解密" + des.decode(decodeStr));
    }

    private String desWithKsy() {
        return "";
    }

    private String desWithNull() {
        return "";
    }

}
